package com.alinesno.cloud.base.storage.service.strategy;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alinesno.cloud.base.storage.entity.StorageFileEntity;
import com.alinesno.cloud.base.storage.service.IStorageFileService;
import com.alinesno.cloud.base.storage.service.StorageService;
import com.alinesno.cloud.base.storage.utils.QiniuStoreHandler;

import cn.hutool.core.lang.UUID;

/**
 * 七牛数据存储方案
 * @author WeiXiaoJin
 * @since 2018年2月23日 下午2:37:50
 */
@Service("qiniuStorageService")
public class QiniuStorageServiceImpl implements StorageService{

	//日志记录
	private final static Logger log = LoggerFactory.getLogger(QiniuStorageServiceImpl.class);

	@Autowired
	private IStorageFileService storageFileService ; 
	
	@Autowired
	private QiniuStoreHandler qiniuStoreHandler ;

	@Override
	public String uploadData(String fileLoalAbcPath , String bucket) {
		log.debug("file loal abc path = {}" , fileLoalAbcPath);
		String path = null;
		try {
			path = qiniuStoreHandler.upload(fileLoalAbcPath);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return path ;
	}

	@Override
	public String downloadData(String fileId , String bucket) {
		log.debug("file id = {}" , fileId);
		String path = null;
		try {
			path = qiniuStoreHandler.privateUrl(fileId);
		} catch (IOException e) {
			log.error("get download url = {}" , e);
		}
		return path ;
	}

	@Override
	public boolean deleteData(String fileId , String bucket) {
		return qiniuStoreHandler.deleteData(fileId);
	}

	@Override
	public StorageFileEntity uploadData(String fileLoalAbcPath, String fileName, String bucket) throws Exception {
		
		StorageFileEntity dbFile = new StorageFileEntity();

		File file = new File(fileLoalAbcPath);
		dbFile.setFileName(fileName);
		dbFile.setFileSize(file.getTotalSpace());

		String path = qiniuStoreHandler.upload(fileLoalAbcPath) ; 
		log.debug("path:{}" , path);
		dbFile.setUrlQiniu(path); 
	
		storageFileService.save(dbFile) ; 
		return dbFile ;
	}

	@Override
	public String presignedUrl(String filePath, String bucket) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String uploadData(byte[] buffer , String suffix) throws Exception {
		File file = new File("/tmp/" + UUID.randomUUID() + suffix) ; 
		FileUtils.writeByteArrayToFile(file, buffer); ; 
		String path = this.uploadData(file.getAbsolutePath(), null) ; 
		log.debug("path = {}" , path);
		file.deleteOnExit(); 
		return path ;
	}

}
